<template>
  <div class="container">
    <Breadcrumb :items="[$t('menu.system'), $t('menu.system.user')]" />
    <a-card class="general-card">
      <a-divider style="margin-top: 0" />
      <a-row style="margin-bottom: 16px">
        <a-col :span="12">
          <a-space>
            <a-button type="primary" @click="add">
              <template #icon>
                <icon-plus />
              </template>
              {{ $t('searchTable.operation.create') }}
            </a-button>
          </a-space>
        </a-col>
        <a-col
          :span="12"
          style="display: flex; align-items: center; justify-content: end"
        >
          <a-tooltip :content="$t('searchTable.actions.refresh')">
            <div class="action-icon" @click="search"
              ><icon-refresh size="18"
            /></div>
          </a-tooltip>
          <a-dropdown @select="handleSelectDensity">
            <a-tooltip :content="$t('searchTable.actions.density')">
              <div class="action-icon"><icon-line-height size="18" /></div>
            </a-tooltip>
            <template #content>
              <a-doption
                v-for="item in densityList"
                :key="item.value"
                :value="item.value"
                :class="{ active: item.value === size }"
              >
                <span>{{ item.name }}</span>
              </a-doption>
            </template>
          </a-dropdown>
          <a-tooltip :content="$t('searchTable.actions.columnSetting')">
            <a-popover
              trigger="click"
              position="bl"
              @popup-visible-change="popupVisibleChange"
            >
              <div class="action-icon"><icon-settings size="18" /></div>
              <template #content>
                <div id="tableSetting">
                  <div
                    v-for="(item, index) in showColumns"
                    :key="item.dataIndex"
                    class="setting"
                  >
                    <div style="margin-right: 4px; cursor: move">
                      <icon-drag-arrow />
                    </div>
                    <div>
                      <a-checkbox
                        v-model="item.checked"
                        @change="
                          handleChange($event, item as TableColumnData, index)
                        "
                      >
                      </a-checkbox>
                    </div>
                    <div class="title">
                      {{ item.title === '#' ? '序列号' : item.title }}
                    </div>
                  </div>
                </div>
              </template>
            </a-popover>
          </a-tooltip>
        </a-col>
      </a-row>
      <a-table
        row-key="id"
        :loading="loading"
        :pagination="pagination"
        :columns="(cloneColumns as TableColumnData[])"
        :data="renderData"
        :bordered="false"
        :size="size"
        @page-change="onPageChange"
      >
        <template #index="{ rowIndex }">
          {{ rowIndex + 1 + (pagination.current - 1) * pagination.pageSize }}
        </template>

        <template #status="{ record }">
          <span v-if="record.status === '1'" class="circle"></span>
          <span v-else class="circle pass"></span>
          {{ $t(`searchTable.form.status.${record.status}`) }}
        </template>

        <template #optional="{ record }">
          <a-button type="text" size="small" @click="changeUser(record)">
            <template #icon>
              <icon-edit />
            </template>
            修改职位
          </a-button>
          <a-popconfirm
            :content="`此操作将永久删除(${record.username}), 是否继续?`"
            type="warning"
            @ok="delUser(record)"
          >
            <a-button
              v-if="record.pid != 0"
              type="text"
              size="small"
              status="danger"
            >
              <template #icon>
                <icon-delete />
              </template>
              删除
            </a-button>
          </a-popconfirm>
        </template>
      </a-table>
    </a-card>
    <MenuForm
      v-model:visible="formDialogVisible"
      :form-data="formData"
      :selected="formModel.selected"
      :fetchData="fetchData"
      :options="options"
      :optionFieldNames="fieldNames"
    />

    <a-modal
      v-model:visible="visible"
      title="Modal Form"
      @cancel="handleCancel"
      @ok="handleClick"
    >
      <a-select
        :options="options"
        :field-names="fieldNames"
        :default-input-value="value"
        @change="changeInfo"
      >
      </a-select>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
  import { computed, ref, reactive, watch, nextTick, onMounted } from 'vue';
  import { useI18n } from 'vue-i18n';
  import useLoading from '@/hooks/loading';
  import { PolicyRecord, PolicyParams } from '@/api/system';
  import { Pagination } from '@/types/global';
  import type { SelectOptionData } from '@arco-design/web-vue/es/select/interface';
  import type { TableColumnData } from '@arco-design/web-vue/es/table/interface';
  import cloneDeep from 'lodash/cloneDeep';
  import Sortable from 'sortablejs';
  import { Message } from '@arco-design/web-vue';
  import MenuForm from './components/menu-form.vue';
  import {
    delUserInfo,
    queryUserList,
    departmentInfo,
    changeUserInfo,
  } from '@/api/system';

  type SizeProps = 'mini' | 'small' | 'medium' | 'large';
  type Column = TableColumnData & { checked?: true };

  const generateFormModel = () => {
    return {
      selected: 'T91',
      number: '',
      name: '',
      contentType: '',
      filterType: '',
      createdTime: [],
      status: '',
    };
  };
  const generateFormAdd = () => {
    return {
      selected: '',
      name: '',
      age: undefined,
      section: '',
    };
  };
  const { loading, setLoading } = useLoading(true);
  const { t } = useI18n();
  const renderData = ref([]);
  const formModel = ref(generateFormModel());
  const formAdd = ref(generateFormAdd());
  const cloneColumns = ref<Column[]>([]);
  const showColumns = ref<Column[]>([]);

  //编辑添加按钮
  const formData = ref();
  console.log(formData);
  // 弹出框标记
  const formDialogVisible = ref(false);
  const add = () => {
    formData.value = {};
    formDialogVisible.value = true;
  };
  const edit = (e: any) => {
    formDialogVisible.value = true;
    console.log(formDialogVisible.value);
    formData.value = { ...e };
  };

  const size = ref<SizeProps>('medium');

  const basePagination: Pagination = {
    current: 1,
    pageSize: 20,
  };
  const pagination = reactive({
    ...basePagination,
  });

  //选择大小
  const densityList = computed(() => [
    {
      name: t('searchTable.size.mini'),
      value: 'mini',
    },
    {
      name: t('searchTable.size.small'),
      value: 'small',
    },
    {
      name: t('searchTable.size.medium'),
      value: 'medium',
    },
    {
      name: t('searchTable.size.large'),
      value: 'large',
    },
  ]);

  //每一列
  const columns = computed<TableColumnData[]>(() => [
    {
      title: t('searchTable.columns.index'),
      dataIndex: 'id',
      align: 'center',
    },
    {
      title: '用户名',
      dataIndex: 'username',
      align: 'center',
    },
    {
      title: '手机号',
      dataIndex: 'phone',
      align: 'center',
    },
    {
      title: '状态',
      dataIndex: 'status',
      align: 'center',
    },
    {
      title: '创建时间',
      dataIndex: 'create_time',
      align: 'center',
    },
    {
      title: '权限名称',
      dataIndex: 'position_name',
      align: 'center',
    },
    {
      title: '操作',
      slotName: 'optional',
      align: 'center',
    },
  ]);

  const contentTypeOptions = computed<SelectOptionData[]>(() => [
    {
      label: t('searchTable.form.contentType.img'),
      value: 'img',
    },
    {
      label: t('searchTable.form.contentType.horizontalVideo'),
      value: 'horizontalVideo',
    },
    {
      label: t('searchTable.form.contentType.verticalVideo'),
      value: 'verticalVideo',
    },
  ]);
  const filterTypeOptions = computed<SelectOptionData[]>(() => [
    {
      label: t('searchTable.form.filterType.artificial'),
      value: 'artificial',
    },
    {
      label: t('searchTable.form.filterType.rules'),
      value: 'rules',
    },
  ]);
  const statusOptions = computed<SelectOptionData[]>(() => [
    {
      label: t('searchTable.form.status.online'),
      value: 'online',
    },
    {
      label: t('searchTable.form.status.offline'),
      value: 'offline',
    },
  ]);

  //获取·数据
  const fetchData = async (
    params: PolicyParams = { current: 1, pageSize: 20 }
  ) => {
    setLoading(true);
    try {
      console.log(params);
      const { data } = await queryUserList(params);
      console.log(data);
      console.log(data.data);
      renderData.value = data;
      pagination.current = params.current;
      pagination.total = 50;
    } catch (err) {
      Message.error(err);
    } finally {
      setLoading(false);
    }
  };

  onMounted(() => {
    fetchData();
  });
  //删除
  const delUser = async (data: any) => {
    console.log(data);
    const deldata = {
      id: data.id,
    };
    await delUserInfo(deldata).then(() => {
      fetchData();
      Message.success('删除成功');
    });
  };

  const search = () => {
    fetchData({
      ...basePagination,
      ...formModel.value,
    } as unknown as PolicyParams);
  };

  const onPageChange = (current: number) => {
    fetchData({ ...basePagination, current });
  };

  const reset = () => {
    formModel.value = generateFormModel();
  };

  const handleSelectDensity = (
    val: string | number | Record<string, any> | undefined,
    e: Event
  ) => {
    size.value = val as SizeProps;
  };

  const handleChange = (
    checked: boolean | (string | boolean | number)[],
    column: Column,
    index: number
  ) => {
    if (!checked) {
      cloneColumns.value = showColumns.value.filter(
        (item) => item.dataIndex !== column.dataIndex
      );
    } else {
      cloneColumns.value.splice(index, 0, column);
    }
  };

  const exchangeArray = <T extends Array<any>>(
    array: T,
    beforeIdx: number,
    newIdx: number,
    isDeep = false
  ): T => {
    const newArray = isDeep ? cloneDeep(array) : array;
    if (beforeIdx > -1 && newIdx > -1) {
      // 先替换后面的，然后拿到替换的结果替换前面的
      newArray.splice(
        beforeIdx,
        1,
        newArray.splice(newIdx, 1, newArray[beforeIdx]).pop()
      );
    }
    return newArray;
  };

  const popupVisibleChange = (val: boolean) => {
    if (val) {
      nextTick(() => {
        const el = document.getElementById('tableSetting') as HTMLElement;
        const sortable = new Sortable(el, {
          onEnd(e: any) {
            const { oldIndex, newIndex } = e;
            exchangeArray(cloneColumns.value, oldIndex, newIndex);
            exchangeArray(showColumns.value, oldIndex, newIndex);
          },
        });
      });
    }
  };

  watch(
    () => columns.value,
    (val) => {
      cloneColumns.value = cloneDeep(val);
      cloneColumns.value.forEach((item, index) => {
        item.checked = true;
      });
      showColumns.value = cloneDeep(cloneColumns.value);
    },
    { deep: true, immediate: true }
  );

  // function fmenu(menuList: any) {
  //   return menuList?.map((item) => {
  //     const { id, pid, cat_name } = item;
  //     console.log(item.cat_name);
  //     const son = item.son ?? [];
  //     const isChild = son != null && son.length !== 0;
  //     const currentArray: any = {
  //       key: id,
  //       title: cat_name,
  //       children: [],
  //     };
  //     // 是否有子菜单，并递归处理
  //     if (isChild) {
  //       currentArray.children = fmenu(son);
  //     }
  //     return currentArray;
  //   });
  // }

  /*
   *@ 修改职位
   */
  const options = ref([]);
  onMounted(() => {
    departmentInfo().then((res) => {
      console.log(res);
      options.value = filter(res.data[0]);
      console.log(options.value);
    });
  });
  const value = ref();
  const fieldNames = { value: 'id', label: 'test' };
  const filter = (v) => {
    const array = v.son;
    const arr = [];
    array.forEach((t) => {
      arr.push({ test: t.name, id: t.id });
    });

    console.log(arr);

    return arr;
  };

  const userInfoId = ref();

  const visible = ref(false);
  const changeUser = (value) => {
    console.log(value);

    userInfoId.value = value.id;
    console.log(userInfoId.value);

    visible.value = true;
  };
  const changeValue = ref();
  const changeInfo = (e) => {
    console.log(e);

    changeValue.value = e;
  };

  const handleClick = async () => {
    const parmes = {
      position_id: changeValue.value,
      admin_id: userInfoId.value,
    };
    console.log(parmes);

    const data: any = await changeUserInfo(parmes);
    console.log(data);
    if (data.code === 200) {
      Message.success('修改成功');
      fetchData();
    }
  };

  const handleCancel = () => {
    visible.value = false;
  };
</script>

=

<style scoped lang="less">
  .container {
    padding: 0 20px 20px 20px;
  }
  :deep(.arco-table-th) {
    &:last-child {
      .arco-table-th-item-title {
        margin-left: 16px;
      }
    }
  }
  .action-icon {
    margin-left: 12px;
    cursor: pointer;
  }
  .active {
    color: #0960bd;
    background-color: #e3f4fc;
  }
  .setting {
    display: flex;
    align-items: center;
    width: 200px;
    .title {
      margin-left: 12px;
      cursor: pointer;
    }
  }
</style>
